package demo.udpClient;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket>{

	private int serverPort;
	public UdpClientHandler(int serverPort) {
		this.serverPort=serverPort;
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("管道激活");
		for(int i=1;i<=1000;i++)
		{
			Thread.sleep(1000);
			ByteBuf msg=Unpooled.copiedBuffer("Hello Server!".getBytes(CharsetUtil.UTF_8));
			//向所有地址发送
			ctx.writeAndFlush(new DatagramPacket(msg, new InetSocketAddress("255.255.255.255",serverPort)));
			System.out.println("发送完第"+i+"次报文!");
		}
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg)
			throws Exception {
		String str=msg.content().toString(CharsetUtil.UTF_8);
		InetSocketAddress sender=msg.sender();
		System.out.println("收到来自"+sender+"的UPD数据:"+str);
	}
	
}
